<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Manage extends BaseModel
{
    use HasFactory;

    const CREATED_AT='create_time';
    const UPDATED_AT='change_time';

    protected $table = 'manage';

    public static $manage_name = 'username';//全局显示的管理员名使用真名


    /**
     * 根据管理员id  获取管理员名称
     * @param manage_id 管理员id
     */
    public function getManageNameByManageId($manage_id){
        return $this->where('id' , $manage_id)->value(self::$manage_name);
    }


    /**
     *  管理员添加
     * @param $data 添加的数据
     */
    public function add($data){
        $this->account = $data->account;
        $this->username = $data->username;
        $this->password = md5($data->password);
        $this->tel = $data->tel;
        $this->manage_id = $data->manage_id;
        $this->is_del = 1;

        return  $this->save();
    }

    /**
     *  修改前言
     * @param $data 添加的数据
     */
    public function change($data){
        $res = $this->where('is_del' , 1)->find($data['id']);
        if(!$res){
            return false;
        }
        $res->username = $data->username;
        $res->tel = $data->tel;

        return  $res->save();
    }


    /**
     * 判断账号是否已经存在
     * @param account 管理员名称
     * @param id 管理员id   可选，主要是用于修改
     */
    public function manageAccountIsExists($account , $id = null){
        $res = $this->where('account' , $account)->where(function($query) use($id){
                if(!empty($id)){
                    $query->where('id' , '<>' , $id);
                }
        })->where('is_del' , 1)->first();
        return $res;
    }



}
